package com.ghxxzx.dagl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ghxxzx.dagl.entity.*;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.*;
import com.ghxxzx.dagl.service.DalrService;
import com.ghxxzx.dagl.utils.PathUtils;
import com.ghxxzx.dagl.utils.WsFlag;
import com.ghxxzx.dagl.vo.ResultEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/api/upload")
public class UploadFjController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    PathUtils pathUtils;
    @Autowired
    private ClxxRgMapper clxxRgMapper;
    @Autowired
    private DaxxRgMapper daxxRgMapper;
    @Autowired
    private DaxxWsRgMapper daxxWsRgMapper;
    @Autowired
    private GryfKjRgMapper gryfKjRgMapper;
    @Autowired
    private DalxMapper dalxMapper;
    @Autowired
    private DalrService dalrService;
    @Autowired
    private ClxxMapper clxxMapper;
    @Autowired
    private WsFlag wsFlag;
    @PostConstruct
    public void init() {
        File file = new File(pathUtils.getPath());
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void checkAndMkdirs(String path) {
        File basePath = new File(path);
        if (!basePath.exists()) {
            basePath.mkdirs();
        }
    }

    private boolean pathFlagCheck(List<ClxxRg> clxxes, String clxxname) {
        boolean flag = false;
        for (ClxxRg clxxRg : clxxes) {
            String name = clxxRg.getWjxh() + clxxRg.getClmc();
            if (name.equals(clxxname)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    @PostMapping("upLoadClxx")
    public ResultEntity upLoadFileBatch(MultipartFile[] files, String lb, String dah) {


        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String basePath = pathUtils.getPath() + "/" + lb + "/" + dah;

//            String code = wsFlag.getCode(dah);
//            Integer integer = dalxMapper.findByCode(code);
            Integer integer = wsFlag.getTypeId(dah);
            HashMap<Integer, Integer> dalxFlag = wsFlag.getDalxFlag();
            Integer integer1 = dalxFlag.get(integer);
            if (integer1==1){
                DaxxRg byDabh = daxxRgMapper.findByDabh(dah);
                if (byDabh==null){
                    throw new JyException("请先录入案卷再上传材料");
                }
            }else if (integer1==2){
                GryfKjRg byDabh = gryfKjRgMapper.findByDabh(dah);
                if (byDabh==null){
                    throw new JyException("请先录入案卷再上传材料");
                }else {
                    checkAndMkdirs(basePath);
                    for (MultipartFile file : files) {
                        String path = basePath + "/";
                        inputStream = file.getInputStream();
                        String originalFilename = file.getOriginalFilename();
                        int i = originalFilename.lastIndexOf("/");
                        String filename = originalFilename.substring(i + 1);
                        if (i != -1) {
//                    int i1 = originalFilename.substring(0, i).lastIndexOf("/");
                            int i2 = originalFilename.substring(0, i).indexOf("/");
                            if (i2 != -1) {
                                String dir2 = originalFilename.substring(i2 + 1, i);
                                checkAndMkdirs(basePath + "/" + dir2);
                                path += dir2 + "/" + filename;
                            } else {
                                path += filename;
                            }
                        }
                        fileOutputStream = new FileOutputStream(path);
                        IOUtils.copy(inputStream, fileOutputStream);
                        fileOutputStream.flush();
                        if (fileOutputStream != null) {
                            fileOutputStream.close();
                        }
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    }
                    return ResultEntity.ok();
                }
            }else if (integer1==3){
                DaxxWsRg byDabh = daxxWsRgMapper.findByDabh(dah);
                if (byDabh==null){
                    throw new JyException("请先录入案卷再上传材料");
                }
            }

            checkAndMkdirs(basePath);
            if (files == null || files.length == 0) {
                return ResultEntity.error("没有文件");
            }
            Set<String> strings = new HashSet<>();
            for (MultipartFile file : files) {
                String filename = file.getOriginalFilename();
                String[] split = filename.split("/");
                if (split.length < 2) {
                    throw new JyException("上传文件夹路径错误");
                }
                String s = split[1];
                int leng = 0;
                if (s.lastIndexOf(".") == -1) {
                    leng = s.length();
                } else {
                    leng = s.lastIndexOf(".");
                }
                String prefix = s.substring(0, leng);
                if (prefix.length() <= 3) {
                    throw new JyException("请检查上传的材料名称是否正确");
                }
                strings.add(prefix);
            }
            for (String string : strings) {
                String substring = string.substring(0, 3);
                boolean numeric = StringUtils.isNumeric(substring);
                if (!numeric) {
                    throw new JyException("请检查上传的材料名称是否正确");
                }
            }
/*            for (MultipartFile file : files) {
                String originalFilename = file.getOriginalFilename();
                int i = originalFilename.lastIndexOf("/");
                String filename = originalFilename.substring(i + 1);
                String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                boolean fileFlag = getFileFlag(suffix);
//                if (!fileFlag) {
//                    throw new JyException("请上传指定格式:bmp,jpg,png,pdf");
//                }
                if (i != -1) {
                    int i1 = originalFilename.substring(0, i).lastIndexOf("/");
                    if (i1 != -1) {
                        String dir2 = originalFilename.substring(i1 + 1, i);
                        checkAndMkdirs(basePath + "/" + dir2);
                        if (suffix.equalsIgnoreCase("pdf")) {
                            throw new JyException("档案编号目录下子级文件夹目录下不允许存在pdf");
                        }
                    }
//                    else {
//                        if (!suffix.equalsIgnoreCase("pdf")) {
//                            throw new JyException("档案编号目录下不允许存在pdf以外的文件");
//                        }
//                    }
                }
            }*/
            ArrayList<ClxxRg> clxxRgs = new ArrayList<>();
            for (String string : strings) {
                String substring = string.substring(0, 3);
                String s = string.substring(3, string.length());
//                String[] split = dah.split("-");
                QueryWrapper<Clxx> clxxQueryWrapper = new QueryWrapper<>();
                clxxQueryWrapper.eq("dabh",dah);
                clxxQueryWrapper.eq("wjxh", substring);
                clxxQueryWrapper.eq("clmc", s);
                Clxx clxx2= clxxMapper.selectOne(clxxQueryWrapper);
                if (clxx2 != null) {
                    throw new JyException("该"+string+"材料信息已入馆");
                }
                QueryWrapper<ClxxRg> wrapper = new QueryWrapper<>();
                wrapper.eq("dabh", dah);
                wrapper.eq("wjxh", substring);
                wrapper.eq("clmc", s);
                ClxxRg selectOne = clxxRgMapper.selectOne(wrapper);
                if (selectOne != null) {
                    continue;
                }
//                String substring1 = split[0].substring(0, split[0].length() - 4);
//                QueryWrapper<Dalx> dalxQueryWrapper = new QueryWrapper<>();
//                dalxQueryWrapper.eq("code", substring1);
                Integer typeId = wsFlag.getTypeId(dah);
                Dalx dalx = dalxMapper.selectById(typeId);
                clxxRgs.add(new ClxxRg(dah, substring, s, dalx.getId(), dalx.getDalxName()));
            }
            dalrService.addClxxs(clxxRgs);
            for (MultipartFile file : files) {
                String path = basePath + "/";
                inputStream = file.getInputStream();
                String originalFilename = file.getOriginalFilename();
                int i = originalFilename.lastIndexOf("/");
                String filename = originalFilename.substring(i + 1);
                if (i != -1) {
//                    int i1 = originalFilename.substring(0, i).lastIndexOf("/");
                    int i2 = originalFilename.substring(0, i).indexOf("/");
                    if (i2 != -1) {
                        String dir2 = originalFilename.substring(i2 + 1, i);
                        checkAndMkdirs(basePath + "/" + dir2);
                        path += dir2 + "/" + filename;
                    } else {
                        path += filename;
                    }
                }
                fileOutputStream = new FileOutputStream(path);
                IOUtils.copy(inputStream, fileOutputStream);
                fileOutputStream.flush();
            }
        } catch (JyException e) {
            log.error(e.getMess(), e);
            return ResultEntity.error(e.getMess());
        }catch (DuplicateKeyException e){
            log.error(e.getMessage(), e);
            return ResultEntity.error("材料已重复，或已上传,请勿重复点击");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultEntity.error("未知异常");
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultEntity.ok();
    }

    public boolean getFileFlag(String suffix) {
        boolean flag = false;
        if (suffix.equalsIgnoreCase("jpg")) {
            flag = true;
        } else if (suffix.equalsIgnoreCase("png")) {
            flag = true;
        } else if (suffix.equalsIgnoreCase("bmp")) {
            flag = true;
        } else if (suffix.equalsIgnoreCase("pdf")) {
            flag = true;
        }
        return flag;
    }
}
